package com.sxf.core.record;

import com.sxf.core.record.dao.SourceRecordMapper;
import com.sxf.core.record.threadlocal.RecordDataThreadLocal;
import com.sxf.core.record.threadlocal.SerialThreadLocal;
import com.sxf.utils.JacksonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @description:
 * @author: zhangyb@ccccit.com.cn
 * @date: 2021年5月14日 上午11:31:47
 */
public class RecordInterceptor implements HandlerInterceptor {

	private static final Logger LOGGER = LoggerFactory.getLogger(HandlerInterceptor.class);

	private SourceRecordMapper sourceRecordMapper;

	public RecordInterceptor(SourceRecordMapper sourceRecordMapper) {
		this.sourceRecordMapper = sourceRecordMapper;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		SerialThreadLocal.set(UUID.randomUUID().toString());
		RecordDataThreadLocal.set(request.getRequestURI(), serialHeader(request));
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		try {
			if(!Objects.isNull(RecordDataThreadLocal.get().getSuccess())) {
				sourceRecordMapper.insert(RecordDataThreadLocal.get());
			}
		} catch (Exception e) {
			LOGGER.error("保持日志文件失败！", e);
		} finally {
			RecordDataThreadLocal.remove();
			SerialThreadLocal.remove();
		}
	}
	
	private String serialHeader(HttpServletRequest request) {
		Map<String, String> headerMap = new HashMap<>();
		Enumeration<String> headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String headerName = headerNames.nextElement();
			headerMap.put(headerName, request.getHeader(headerName));
		}
		return JacksonUtils.toJsonString(headerMap);
	}

}
